Factorial of a non-negative number n is expressed as n!.
Mathematically, Factorial is defined as:
By default, the factorial of zero is defined to be 1.
For example, if you have to find the factorial of 5, multiple all positive integers less than or equal to 5.
There are a few ways to write the code to find out the factorial in the C++
language.
The following code is the easiest way to find the n!
of number n.
#include <iostream> using namespace std; int main() { int f = 1, n; cout<<"Please enter a number : "; cin>>n; for(int i=1; i<=n ; i++) f = f*i; cout<<n<<"! = "<<f<<endl; return 0; }
The code seems simple. Right?
But there is one small problem with this code.
It cannot determine the factorial of a large number. If you enter a large number such as 100, the code produces an incorrect answer.
For example, for some random numbers, the code produces the following output:
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 1932053504
Till 12!, the code produces correct output, but when the number becomes larger than that, the code doesn’t produce the desired output.
The problem lies in the size of the output. Factorial of a large number has more digits than an Integer or even Long data type can contain.
An integer is 4 byte and can only contain -2147483648 to +2147483647
Find a factorial for a large number using C++
Here is an alternative method to find factorial of any number.
#include<iostream> using namespace std; #define SIZE 500 int multiply(int x, int f[], int digits); void factorial(int n) { int f[SIZE]; f[0] = 1; int digits = 1; for (int x=2; x<=n; x++) { digits = multiply(x, f, digits); } cout<<n<<"! = "; for (int i=digits-1; i>=0; i--) cout << f[i]; } int multiply(int x, int f[], int digits) { int carry = 0; for (int i=0; i<digits; i++) { int prod = f[i] * x + carry; f[i] = prod % 10; carry = prod/10; } while (carry) { f[digits] = carry%10; carry = carry/10; digits++; } return digits; } int main() { int n; cout<<"Please enter a number : "; cin>>n; factorial(n); return 0; }
Comments